package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.TbDevice;
import com.ruoyi.system.domain.TbRoomDevice;
import com.ruoyi.system.domain.TbSt;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TbDeviceMapper;
import com.ruoyi.system.mapper.TbRoomDeviceMapper;
import com.ruoyi.system.mapper.TbStMapper;
import com.ruoyi.system.netty.NettyTcpServer;
import com.ruoyi.system.service.ITbRoomDeviceService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 房间设备学生成绩记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-25
 */
@Service
@Slf4j
public class TbRoomDeviceServiceImpl implements ITbRoomDeviceService {
    @Autowired
    private TbRoomDeviceMapper tbRoomDeviceMapper;

    @Autowired
    TbDeviceMapper tbDeviceMapper;

    @Autowired
    TbStMapper tbStMapper;


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询房间设备学生成绩记录
     *
     * @param id 房间设备学生成绩记录主键
     * @return 房间设备学生成绩记录
     */
    @Override
    public TbRoomDevice selectTbRoomDeviceById(Long id) {
        return tbRoomDeviceMapper.selectTbRoomDeviceById(id);
    }

    /**
     * 查询房间设备学生成绩记录列表
     *
     * @param tbRoomDevice 房间设备学生成绩记录
     * @return 房间设备学生成绩记录
     */
    @Override
    public List<TbRoomDevice> selectTbRoomDeviceList(TbRoomDevice tbRoomDevice) {
        return tbRoomDeviceMapper.selectTbRoomDeviceList(tbRoomDevice);
    }

    @Override
    public List<TbRoomDevice> selectOnlineRoom(TbRoomDevice tbRoomDevice) {
        return tbRoomDeviceMapper.selectOnlineRoom(tbRoomDevice);
    }

    /**
     * 新增房间设备学生成绩记录
     *
     * @param tbRoomDevice 房间设备学生成绩记录
     * @return 结果
     */
    @Override
    public int insertTbRoomDevice(TbRoomDevice tbRoomDevice) {

        return tbRoomDeviceMapper.insertTbRoomDevice(tbRoomDevice);
    }

    /**
     * 修改房间设备学生成绩记录
     *
     * @param tbRoomDevice 房间设备学生成绩记录
     * @return 结果
     */
    @Override
    public int updateTbRoomDevice(TbRoomDevice tbRoomDevice) {
        return tbRoomDeviceMapper.updateTbRoomDevice(tbRoomDevice);
    }

    /**
     * 批量删除房间设备学生成绩记录
     *
     * @param ids 需要删除的房间设备学生成绩记录主键
     * @return 结果
     */
    @Override
    public int deleteTbRoomDeviceByIds(Long[] ids) {
        return tbRoomDeviceMapper.deleteTbRoomDeviceByIds(ids);
    }

    /**
     * 删除房间设备学生成绩记录信息
     *
     * @param id 房间设备学生成绩记录主键
     * @return 结果
     */
    @Override
    public int deleteTbRoomDeviceById(Long id) {
        return tbRoomDeviceMapper.deleteTbRoomDeviceById(id);
    }

    @Override
    public void dosomething(String msg, String ip) {
        // todo 处理ue消息
        log.info("tcp 消息");
        // 根据id获取房间
        TbDevice tbDevice = new TbDevice();
        tbDevice.setIp(ip);
        List<TbDevice> tbDevices = tbDeviceMapper.selectTbDeviceList(tbDevice);
        if (CollectionUtils.isEmpty(tbDevices)) {
            return;
        }
        TbDevice tbDevice1 = tbDevices.get(0);
        //
        TbRoomDevice tbRoomDevice = new TbRoomDevice();
        tbRoomDevice.setState("0");
        tbRoomDevice.setDeviceId(Long.valueOf(tbDevice1.getId()));
        List<TbRoomDevice> tbRoomDevices = tbRoomDeviceMapper.selectTbRoomDeviceList(tbRoomDevice);
        if (CollectionUtils.isEmpty(tbRoomDevices)) {
            return;
        }
        TbRoomDevice tbRoomDevice1 = tbRoomDevices.get(0);
        tbRoomDevice1.setOnLineState("0");
        //todo 修改属性信息
        // todo 新增操作记录
        log.info("更新记录");
        tbRoomDeviceMapper.updateTbRoomDevice(tbRoomDevice1);
    }

    @Override
    public JSONObject getSt(String ip) {
        JSONObject jsonObject = new JSONObject();
        log.info("设备注册成功  返回题目  消息");
        // 根据id获取房间
        TbDevice tbDevice = new TbDevice();
        tbDevice.setIp(ip);
        List<TbDevice> tbDevices = tbDeviceMapper.selectTbDeviceList(tbDevice);
        if (CollectionUtils.isEmpty(tbDevices)) {
            return jsonObject;
        }
        TbDevice tbDevice1 = tbDevices.get(0);
        //
        TbRoomDevice tbRoomDevice = new TbRoomDevice();
        tbRoomDevice.setState("0");
        tbRoomDevice.setDeviceId(Long.valueOf(tbDevice1.getId()));
        List<TbRoomDevice> tbRoomDevices = tbRoomDeviceMapper.selectTbRoomDeviceList(tbRoomDevice);
        if (CollectionUtils.isEmpty(tbRoomDevices)) {
            return jsonObject;
        }
        TbRoomDevice tbRoomDevice1 = tbRoomDevices.get(0);
        Long stId = tbRoomDevice1.getStId();
        TbSt tbSt = tbStMapper.selectTbStById(stId);
        jsonObject.put("tm", tbSt.getCode());
        return jsonObject;
    }


    @Override
    public TbDevice getDevice(String ip) {
        log.info("设备注册成功  返回题目  消息");
        // 根据id获取房间
        TbDevice tbDevice = new TbDevice();
        tbDevice.setIp(ip);
        List<TbDevice> tbDevices = tbDeviceMapper.selectTbDeviceList(tbDevice);
        if (CollectionUtils.isEmpty(tbDevices)) {
            return null;
        }
        return tbDevices.get(0);

    }

    @Override
    public SysUser tcpUserLogin(JSONObject jsonObject) {
        String user = jsonObject.getString("user");
        String userpassword = jsonObject.getString("password");
        boolean login = this.login(user, userpassword);
        if (login) {
            SysUser sysUser = sysUserMapper.selectUserByUserName(user);
            return sysUser;
        }
        return null;
    }


    /**
     * 向指定设备发送指令
     * @param deviceId 设备ID
     * @param command  指令字符串
     * @return 是否发送成功
     */
    public boolean sendCommandToDevice(String deviceId, String command) {
        Channel channel = NettyTcpServer.deviceChannelMap.get(deviceId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(command + "\n");
            return true;
        } else {
            System.out.println("设备未连接或连接无效: " + deviceId);
            return false;
        }
    }


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public boolean login(String username, String password) {
        // 验证码校验
        //validateCaptcha(username, code, uuid);
        // 登录前置校验
        // 用户验证
        Authentication authentication = null;
        try {
            SysUser sysUser = sysUserMapper.selectUserByUserName(username);
            if (sysUser == null) {
                return false;
            }
            return checkUserPassword(username,password);
        } catch (Exception e) {
            return false;
        } finally {

        }
    }


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectUserByUserName(username); // 根据用户名查询用户信息
        if (sysUser == null) {
            throw new UsernameNotFoundException("User not found");
        }
        List<GrantedAuthority> authorities = new ArrayList<>(); // 设置角色和权限等
        // 例如：authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new org.springframework.security.core.userdetails.User(sysUser.getUserName(), sysUser.getPassword(), authorities);
    }


    public boolean checkUserPassword(String username, String rawPassword) {
        SysUser user = sysUserMapper.selectUserByUserName(username);
        if (user == null) {
            return false;
        }
        String encodedPassword = user.getPassword(); // 数据库中加密后的密码
        // 使用PasswordEncoder校验明文密码和加密密码是否匹配
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


}
